<template>
	<el-icon v-if="isElementIcon && nonexistentName" :size="size" :color="color" :class="{
		'is-loading': loading,
	}" :style="style">
		<component :is="iconName" />
	</el-icon>
	<img v-else-if="nonexistentName" :src="isSelfIcon ? iconName : name" :style="style" />
</template>

<script setup>
import { computed } from "vue"
import { elementIconsKey } from "/plugins/icons"
import selfIconKey from "/plugins/icons/static"
import { hump2short } from "/plugins/path"


const props = defineProps({
	name: {
		type: [String],
		default: ""
	},
	size: {
		type: [String, Number],
		default: 30
	},
	color: {
		type: [String],
		default: ""
	},
	style: {
		type: [String]
	},
	loading: {
		type: [Boolean],
		default: false
	},
	right: {
		type: [Boolean],
		default: false
	},
	left: {
		type: [Boolean],
		default: false
	},
})


const nonexistentName = computed(() => {
	if (["", undefined, null, "undefined", "null"].includes(props.name)) {
		return false
	}
	return true
})

const filename = computed(() => hump2short(formatName.value))
const extname = computed(() => selfIconKey[filename.value])
const fullFilename = computed(() => {
	return filename.value + "." + extname.value
})

const formatName = computed(() => {
	if (!props.name) {
		return ""
	}
	return props.name.replace(/^el\-icon\-/, "")
})
const isElementIcon = computed(() => {
	return elementIconsKey.some(key => hump2short(key).toLocaleLowerCase() === filename.value.toLocaleLowerCase())
})
const isSelfIcon = computed(() => !!extname.value)

const iconName = computed(() => {
	if (isElementIcon.value) {
		return filename.value
	}
	return "/icons/" + fullFilename.value
})
const style = computed(() => ({
	width: typeof props.size === "number" ? props.size + "px" : props.size,
	height: typeof props.size === "number" ? props.size + "px" : props.size,
	color: props.color,
	marginRight: props.right ? "5px" : "",
	marginLeft: props.left ? "5px" : "",
}))
</script>

<style lang="scss" scoped></style>
